/*
 * Copyright 2020 Liu Jie <jieliu2000@live.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.beyondsoft.sabg.edu.configure.sercurity;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtTokenFilter extends OncePerRequestFilter {

    private JwtTokenProvider jwtTokenProvider;

    public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }

    public static final String HEADER_AUTHORIZATION_KEY = "Authorization";

    @Override
    public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) req;
        String bearerToken = servletRequest.getHeader(HEADER_AUTHORIZATION_KEY);
        if (StringUtils.isEmpty(bearerToken)) {
            bearerToken = req.getParameter(HEADER_AUTHORIZATION_KEY);
        }
        if (StrUtil.isNotBlank(bearerToken) && !"null".equalsIgnoreCase(bearerToken)) {
            String token = jwtTokenProvider.resolveToken(bearerToken);
            if (StrUtil.isNotBlank(token) && !"null".equalsIgnoreCase(token)) {
                try {
                    Authentication auth = jwtTokenProvider.getAuthentication(token);
                    if (auth != null) {
                        SecurityContextHolder.getContext().setAuthentication(auth);
                    }
                } catch (Exception e) {
                    log.error("JWT failed",e);
                    SecurityContextHolder.clearContext();
                    HttpServletResponse httpRes = (HttpServletResponse) res;
                    httpRes.sendError(401, StrUtil.format("jwt token verify failed,token:{},Access Denied:{}", token, e.getMessage()));
                    return;
                }
            }

        }

        filterChain.doFilter(req, res);
    }
}
